<?php 

/**
 * 
 * Main function to add the site urls
 * 
 * Gets related labels recurrently
 * 
 * @param $labels
 * @param $depth
 * @param $xmlstring
 * @param $filepath
 * @param $i
 * @param $nfile
 * @param $output The outputs manager
 */
function add_related($labels, $depth, &$xmlstring, &$filepath, &$i, &$nfile, $output) {
    global $DB_LANG, $CONFIG;

    // TODO: Remove it to create a BIG BIG sitemap
    if ($depth > $CONFIG->maxsitemapdepth) {
    	return false;
    }
    
    if (!$labels) {
        die('WTF! $labels empty?');
    }
    
    $sql = "SELECT DISTINCT el.labelid FROM entrylabels el ";
    
    $sql .= getLabelsSubqueries($labels);

    // Ordered by label name to be able to discard repeated relations
    $sql .= "ORDER BY el.labelid DESC";
    
    $results = $DB_LANG->selectResponses($sql);
    foreach ($results as $result) {
        
    	// Already added?
        $alreadyadded = false;
        foreach ($labels as $breadcrumblabel) {

        	if (!empty($alreadyadded)) {
        		continue;
        	}
        	
        	// To this breadcrumb
            if ($result->labelid == $breadcrumblabel) {
                $alreadyadded = true;
            }
            
            // Relation already added (they are ordered
            if (strcmp($result->labelid, $breadcrumblabel) > 0) {
                $alreadyadded = true;
            }

        }
        
        if (!empty($alreadyadded)) {
            continue;
        }
        $resultlabels = $labels;
        $resultlabels[] = $result->labelid;

        // Minimum priority 0.1 and the priority depends basically on the labels depth (less changes)
        $priority = max(round((1 / intval($depth)), 1), 0.1);
        
	    // Adding the label
	    $xmlstring.= '  <url>'.LB;
	    $xmlstring.= '    <loc>'.$output->link_output(decode_text(implode('-', $resultlabels))).'</loc>'.LB;
	    $xmlstring.= '    <lastmod>'.strftime('%Y-%m-%d').'</lastmod>'.LB;
	    $xmlstring.= '    <changefreq>monthly</changefreq>'.LB;
	    $xmlstring.= '    <priority>'.$priority.'</priority>'.LB;
	    $xmlstring.= '  </url>'.LB;

        $i++;

	    // The maximum number of urls in a XML is 50000 and 10M (with 499999 it reach 10MB)
	    if ($i == 49990) {
	        add_sitemap($xmlstring, $filepath, $i, $nfile);
	    }

        // Adding the related labels
        add_related($resultlabels, ($depth + 1), $xmlstring, $filepath, $i, $nfile, $output);
    }
}



function add_sitemap(&$xmlstring, &$filepath, &$i, &$nfile) {

	global $CONFIG;
	
	// Closing sitemap
    $xmlstring.= '</urlset>';
    create_sitemap($filepath, $xmlstring);
    
    echo 'Memory usage -> close '.$filepath.': '.memory_get_usage().LB;
    
    // Next sitemap
    $nfile++;
    $i = 0;
    $filepath = $CONFIG->datadir.'/sitemaps/'.$_SESSION['lang'].'/sitemap_'.$nfile.'.xml';
    $xmlstring = '<?xml version="1.0" encoding="UTF-8"?>'.LB.'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'.LB;
}


/**
 * Stores $xmlstring into filesystem
 * 
 * @param string $filepath XML filepath
 * @param string $xmlstring XML content
 */
function create_sitemap($filepath, $xmlstring) {
	
	$fh = fopen($filepath, 'w');
	fwrite($fh, $xmlstring);
	fclose($fh);
}
